﻿using System;
using System.IO;
using GalaSoft.MvvmLight;

namespace Gumini.JulaDB.Navigator.Logic
{
    public class ScriptProvider : ObservableObject
    {
        public void Open(string path)
        {
            if (this.IsOpened)
                throw new InvalidOperationException("File is already opened");
            this.Text = File.ReadAllText(path);
            this.IsOpened = true;
            this.Path = path;
        }

        public void Save()
        {
            File.WriteAllText(this.Path, this.Text);
        }

        public void Close()
        {
            if (this.IsOpened)
                throw new InvalidOperationException("File is not opened");
            this.IsOpened = false;
            this.Text = null;
            this.Path = null;
        }

        public string Path
        {
            get { return _path; }
            private set
            {
                if (value != _path)
                {
                    _path = value;
                    RaisePropertyChanged("Path");
                }
            }
        }
        string _path = null;

        public string Text
        {
            get { return _text; }
            set
            {
                if (value != _text)
                {
                    _text = value;
                    RaisePropertyChanged("Text");
                }
            }
        }
        string _text = null;

        /// <summary>
        /// True, if the script file is opened.
        /// </summary>
        public bool IsOpened
        {
            get { return _isOpened; }
            private set
            {
                if (value != _isOpened)
                {
                    _isOpened = value;
                    RaisePropertyChanged("IsOpened");
                    if (_isOpened && FileOpened != null)
                        FileOpened(null, EventArgs.Empty);
                }
            }
        }
        bool _isOpened = false;

        public EventHandler FileOpened;
    }
}
